from flask import Blueprint, jsonify, request, json
import orgMgmt.orgOperation.ocptOprt as ocpOprt
import datetime

ocp = Blueprint('ocp', __name__)


@ocp.route('/init', methods=['GET'])
def init():
    if ocpOprt.getAllOcp() == 0:
        return ocpOprt.getAllOcp()
    else:
        ocplist = []
        for line in ocpOprt.getAllOcp():
            ocplist.append({"ocp_id": line[0], "ocp_name": line[1],
                              "ocp_information": line[2]})
        print(ocplist)
    return jsonify(ocplist)


@ocp.route('/newocp', methods=['POST'])
def newocp():
    print("new a occupation")
    data = request.get_data()
    print(data)
    json_data = json.loads(data.decode("utf-8"))

    if ocpOprt.newocp(json_data.get('ocp_name'), json_data.get('ocp_information')):
        return jsonify(1)
    else:
        return jsonify(2)


@ocp.route('/editocp', methods=['POST'])
def editocp():
    print("edit occupation")
    data = request.get_data()
    print(data)
    json_data = json.loads(data.decode("utf-8"))

    if ocpOprt.editocp(json_data.get('ocp_id'), json_data.get('ocp_name'), json_data.get('ocp_information')):
        return jsonify(1)
    else:
        return jsonify(2)


@ocp.route('/delete', methods=['POST'])
def ocpDelete():
    data = request.get_data()
    print(data)
    word = data.decode("utf-8")
    print(word)
    if ocpOprt.deleteOcp(word):
        return jsonify(1)
    else:
        return jsonify(2)


@ocp.route('/select', methods=['POST'])
def ocpVagueSelect():
    data = request.get_data()
    json_data = json.loads(data.decode("utf-8"))
    word = json_data.get('word')
    ocplist = []
    if ocpOprt.searchOcp(word) == 0:
        return jsonify(0)
    else:
        for line in ocpOprt.searchOcp(word):
            ocplist.append({"ocp_id": line[0], "ocp_name": line[1],
                              "ocp_information": line[2]})
        print(ocplist)
        return jsonify(ocplist)
